var redisClient = require('./redis/redisClient')

//获取装备信息
exports.getEquipmentInfo = function(pid, cb) {
	redisClient.hget(pid + ':equip', function(err, res) {
		if (res) {
			for (let i in res) {
				let equipment = res[i]
				equipment = JSON.parse(equipment)
				equipment = equipment ? new EquipmentComponent(equipment) : 0
			}
			cb(res)
		} else {
			cb(null)
		}
	})
}

//获取背包
exports.getBagInfo = function(pid, cb) {
	redisClient.smembers(pid + ':bag', function(err, res) {
		if (res) {
			for (let itemConponent of res) {
				itemConponent = JSON.parse(itemConponent)
				if (itemConponent.baseInfo.type < 30) {
					//武器
					itemConponent = new EquipmentComponent(itemConponent)
				} else {
					//道具
					itemConponent = new ItemComponent(itemConponent)
				}
			}
			cb(res)
		} else {
			cb(null)
		}
	})
}

//获取角色基本信息
exports.getBasicInfo = function(pid, cb) {
	redisClient.hget(pid + ':bInfo', function(err, res) {
		if (res) {
			res = JSON.parse(res)
			cb(res)
		} else {
			cb(null)
		}
	})
}

//保存角色基本信息
exports.savePlayerInfo = function(player) {
	//保存玩家基础信息
	let playerStr = JSON.stringify(player, function(key, value) {
		if (key === basicInfo) {
			return value
		} else {
			return null
		}
	})
	redisClient.set(player.id + ':bInfo', playerStr)
		//保存玩家背包
	for (let i in player.bag.items) {
		let item = player.bag.items[i]
		if (!item) {
			continue
		}
		item.pos = i
		let bagStr = JSON.stringify(item, function(key, value) {
			if (key === baseInfo) {
				return null
			} else {
				return value
			}
		})
		redisClient.sadd(player.id + ':bag', bagStr)
	}
	//保存玩家的穿戴装备信息
	for (let i in player.equipments) {
		let equipment = player.equipments[i]
		let equipmentStr = JSON.stringify(equipment, function(key, value) {
			if (key === baseInfo) {
				return null
			} else {
				return value
			}
		})
		redisClient.sadd(player.id + ':equip', equipmentStr)
	}
}
